/**
 * 统一的HTTP请求工具
 * 自动处理token认证
 */

/**
 * 发送HTTP请求
 * @param {string} url - 请求URL
 * @param {Object} options - 请求选项
 * @returns {Promise<Object>} 返回响应数据
 */
export const request = async(url, options = {}) => {
    // 获取token
    const token = localStorage.getItem('accessToken')

    // 构建请求头
    const headers = {
        'Content-Type': 'application/json',
        ...options.headers
    }

    // 如果有token，添加到Authorization头
    if (token) {
        headers['Authorization'] = `Bearer ${token}`
    }

    try {
        const response = await fetch(url, {
            ...options,
            headers
        })

        if (!response.ok) {
            throw new Error(`请求失败: ${response.status} ${response.statusText}`)
        }

        const data = await response.json()

        // 检查业务状态码
        if (data.code !== 200) {
            // token过期或无效，跳转到登录页
            if (data.code === 401 || data.code === 403) {
                localStorage.removeItem('accessToken')
                localStorage.removeItem('refreshToken')
                localStorage.removeItem('isLoggedIn')
                window.location.href = '/login'
                throw new Error('登录已过期，请重新登录')
            }
            throw new Error(data.message || '请求失败')
        }

        return data
    } catch (error) {
        console.error('请求错误:', error)
        throw error
    }
}

/**
 * GET请求
 */
export const get = (url, params = {}) => {
    const queryString = new URLSearchParams(params).toString()
    const fullUrl = queryString ? `${url}?${queryString}` : url
    return request(fullUrl, { method: 'GET' })
}

/**
 * POST请求
 */
export const post = (url, data = {}) => {
    return request(url, {
        method: 'POST',
        body: JSON.stringify(data)
    })
}

/**
 * PUT请求
 */
export const put = (url, data = {}) => {
    return request(url, {
        method: 'PUT',
        body: JSON.stringify(data)
    })
}

/**
 * DELETE请求
 */
export const del = (url) => {
    return request(url, { method: 'DELETE' })
}

/**
 * 文件上传请求（支持FormData）
 * @param {string} url - 请求URL
 * @param {FormData} formData - 表单数据
 * @returns {Promise<Object>} 返回响应数据
 */
export const upload = async(url, formData) => {
    // 获取token
    const token = localStorage.getItem('accessToken')

    // 构建请求头（不设置Content-Type，让浏览器自动设置multipart/form-data边界）
    const headers = {}

    // 如果有token，添加到Authorization头
    if (token) {
        headers['Authorization'] = `Bearer ${token}`
    }

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers,
            body: formData
        })

        if (!response.ok) {
            throw new Error(`请求失败: ${response.status} ${response.statusText}`)
        }

        const data = await response.json()

        // 检查业务状态码
        if (data.code !== 200 && data.errcode === undefined) {
            // token过期或无效，跳转到登录页
            if (data.code === 401 || data.code === 403) {
                localStorage.removeItem('accessToken')
                localStorage.removeItem('refreshToken')
                localStorage.removeItem('isLoggedIn')
                window.location.href = '/login'
                throw new Error('登录已过期，请重新登录')
            }
            throw new Error(data.message || '请求失败')
        }

        return data
    } catch (error) {
        console.error('上传错误:', error)
        throw error
    }
}

/**
 * 获取带token的代理图片URL
 * @param {string} baseUrl - 代理服务器基础URL
 * @param {string} imageUrl - 原始图片URL
 * @returns {string} 带token的完整代理URL
 */
export const getProxyImageUrl = (baseUrl, imageUrl) => {
    const token = localStorage.getItem('accessToken')
    const encodedImageUrl = encodeURIComponent(imageUrl)

    if (token) {
        return `${baseUrl}?token=${encodeURIComponent(token)}&url=${encodedImageUrl}`
    }
    return `${baseUrl}?url=${encodedImageUrl}`
}

/**
 * 获取当前用户的accessToken
 * @returns {string|null} 返回token或null
 */
export const getAccessToken = () => {
    return localStorage.getItem('accessToken')
}